﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace APIBetaSeries.Models
{
    public class ObjetBase
    {
        public Int64 Code { get; set; }
        public IList<Error> Errors { get; set; }

        public ObjetBase(XDocument value)
        {
            if (value != null)
            {
                XElement root = value.Element("root");
                if (root != null)
                {
                    foreach (XElement element in root.Elements())
                    {
                        if (element.Name == "code")
                        {
                            Code = Convert.ToInt64(element.Value);
                        }
                        if (element.Name == "errors")
                        {
                            IEnumerable<XElement> elementErrors = element.Elements("error");
                            foreach (XElement elementError in elementErrors)
                            {
                                XElement xCode = elementError.Element("code");
                                XElement xContent = elementError.Element("content");
                                Error error = null;
                                if (xCode != null && xContent != null)
                                {
                                    error = new Error
                                        {
                                            Code = Convert.ToInt64(xCode.Value),
                                            Content = xContent.Value
                                        };
                                }
                                if (error != null)
                                {
                                    if (Errors == null)
                                    {
                                        Errors = new List<Error>();
                                    }
                                    Errors.Add(error);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
